package com.jing.ads.receiver;

import java.util.Timer;
import java.util.TimerTask;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.jing.ads.R;
import com.jing.ads.log.Logger;
import com.jing.ads.model.PushAppInfo.AppDetail;
import com.jing.ads.services.QueueService;
import com.jing.ads.util.GlobalUtil;
import com.jing.ads.util.NetworkUtil;
import com.jing.ads.util.NotificationUtil;
import com.jing.ads.util.PreferenceUtil;

public class MainReceiver extends BroadcastReceiver {
	public static final String ACTION_NET_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE";
	public static final String ACTION_BOOT = "android.intent.action.BOOT_COMPLETED";
	public static final String ACTION_LAUNCHER = "com.jing.ads.launcher";

	@Override
	public void onReceive(final Context context, Intent intent) {
		String action = intent.getAction();
//		Toast.makeText(context, action, Toast.LENGTH_LONG).show();
		if (ACTION_NET_CHANGE.equals(action) || ACTION_BOOT.equals(action)) {
			if (NetworkUtil.hasInternet(context)) {
				long receive = PreferenceUtil.getSharedLong(context, "RECEIVE",
						0);
				long ct = System.currentTimeMillis();
				if (Math.abs(ct - receive) <= 5000) {
					return;
				}
				PreferenceUtil.putSharedLong(context, "RECEIVE", ct);
				if (Logger.isDebug) {
					// Toast.makeText(context, "接收网络连接启动",
					// Toast.LENGTH_SHORT).show();
				}
				if (!GlobalUtil.isServiceRunning(context,
						QueueService.class.getName())) {
					Intent ii = new Intent(context, QueueService.class);
					context.startService(ii);
				}
				TimerTask ttt = new TimerTask() {

					@Override
					public void run() {
						Intent b = new Intent(QueueService.ACTION_QUEUE);
						context.sendBroadcast(b);
					}
				};
				Timer t = new Timer();
				t.schedule(ttt, 2000);
				
			}
		} else if (ACTION_LAUNCHER.equals(action)) {
//			Toast.makeText(context, "app launcher!", Toast.LENGTH_LONG).show();
			System.out.println("app launch !");
		} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
			String packageName = intent.getDataString();
			Toast.makeText(context, packageName, Toast.LENGTH_LONG).show();
			AppDetail app = new AppDetail();
			app.packageName = packageName;
			GlobalUtil.setAppDownloadStatus(context.getContentResolver(), app);
			if (app.downloadStatus == AppDetail.DOWNLOADED) {
				String content = context.getString(R.string.notify_active, app.appName);
				NotificationUtil.getInstance(context).showNotify(app.appName, content, packageName, false);
			}
		} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
//			String packageName = intent.getDataString();
		}
	}
}
